"""
Case Type   : reindex
Case Name   : 对表重建索引的同时删除表，发生死锁
Create At   : 2021/12/13
Owner       : zou_jialiang050
Description :
    1.建表插入数据
    2.开启2个会话,同时执行reindex index concurrently,drop table
    3.清理环境
Expect      :
    1.成功
    2.发生死锁，执行成功
    3.成功
History     :
"""

import os
import time
import unittest
from yat.test import Node
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread
from testcase.utils.Logger import Logger


class SQL(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f'-----{os.path.basename(__file__)} start-----')
        self.dbuserNode = Node('PrimaryDbUser')
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.table = 't_reindex_concurrently_0057'
        self.index = 'i_reindex_concurrently_0057'
        self.Constant = Constant()

    def test_reindex(self):
        step1 = '----step1:建表 expect:成功----'
        self.logger.info(step1)
        sql_cmd = f"drop table if exists {self.table};" \
                  f"create table {self.table}(i int);" \
                  f"insert into {self.table} values(" \
                  f"generate_series(1,20000000));" \
                  f"create index {self.index} on {self.table}(i);"
        sql_res = self.primary_sh.execut_db_sql(sql_cmd)
        self.logger.info(sql_res)
        self.assertIn(self.Constant.CREATE_TABLE_SUCCESS, sql_res, "建表失败")
        self.assertIn(self.Constant.INSERT_SUCCESS_MSG, sql_res, "插入失败")
        self.assertIn(self.Constant.CREATE_INDEX_SUCCESS, sql_res, "建索引失败")

        step4 = '----step2:同时执行reindex index concurrently,drop table;' \
                'expect:发生死锁----'
        self.logger.info(step4)
        reindex1 = f'reindex table concurrently {self.table};' \
                   f'select pg_sleep(20);'
        session1 = ComThread(self.primary_sh.execut_db_sql, args=(reindex1,))
        session1.setDaemon(True)

        reindex2 = f'drop table {self.table};'
        session2 = ComThread(self.primary_sh.execut_db_sql, args=(reindex2,))
        session2.setDaemon(True)

        session1.start()
        time.sleep(2)
        session2.start()
        session1.join(200)
        session2.join(200)
        result1 = session1.get_result()
        self.logger.info(result1)
        result2 = session2.get_result()
        self.logger.info(result2)
        self.assertIn('ERROR:  deadlock detected', result1, "执行失败" + step4)
        self.assertIn('DROP TABLE', result2, "执行失败" + step4)

    def tearDown(self):
        step5 = '----step5:清理环境 expect:成功----'
        self.logger.info(step5)
        sql_cmd = f"drop table if exists {self.table};"
        sql_res = self.primary_sh.execut_db_sql(sql_cmd)
        self.logger.info(sql_res)
        self.assertIn(self.Constant.DROP_TABLE_SUCCESS, sql_res, "建表失败")
        self.logger.info(f'-----{os.path.basename(__file__)} end-----')
